<template>
  <div>
    <el-form >
      <el-form-item label="资源名称">
        <el-input v-model="form.name"></el-input>
      </el-form-item>
      <el-form-item label="资源路径">
        <el-input v-model="form.url"></el-input>
      </el-form-item>
      <el-form-item label="资源分类">
        <el-select v-model="form.categoryId" placeholder="请选择上级资源">
          <el-option
            :label="item.name"
            :value="item.id"
            v-for="item in resourceCategoriesList"
            :key="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="描述">
        <el-input v-model="form.description"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button @click="$emit('cancel')">取消</el-button>
        <el-button type="primary" @click="onSubmit">确认</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts">
import Vue from 'vue'
import { getResourceById, saveOrderUpdate } from '@/services/resource'
import { getResourceCategories } from '@/services/resource-category'

export default Vue.extend({
  name: 'ResourceCreateOrEdit',
  props: {
    resourceId: {
      type: [String, Number]
    },
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      form: {
        name: '',
        categoryId: undefined,
        url: '',
        description: ''
      },
      resourceCategoriesList: []
    }
  },

  created () {
    if (this.isEdit) {
      this.loadResourceInfo()
    }
    this.loadResourceCategoryInfo()
  },

  methods: {
    async loadResourceInfo () {
      const { data } = await getResourceById(this.resourceId)
      if (data.code === '000000') {
        this.form = data.data
      }
    },
    async loadResourceCategoryInfo () {
      const { data } = await getResourceCategories()
      if (data.code === '000000') {
        this.resourceCategoriesList = data.data
      }
    },
    async onSubmit () {
      // 1. 表单验证
      // 2. 验证通过，提交表单
      const { data } = await saveOrderUpdate(this.form)
      if (data.code === '000000') {
        this.$message.success('操作成功')
        this.$emit('success')
      }
    }
  }
})
</script>

<style lang="scss" scoped></style>
